package com.life.notes.config.utils;

import com.alibaba.fastjson.JSON;
import com.life.notes.config.constant.ResultEnum;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletResponse;
import java.io.PrintWriter;
import java.util.Date;

/**
 * @author lishuqian
 * @date 2020/6/15
 */
@Slf4j
public class ResponseMsgUtil {

    public ResponseMsgUtil() {
    }

    public static BaseResponse success(Object object) {
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setCode(ResultEnum.SUCCESS.getCode());
        baseResponse.setMsg(ResultEnum.SUCCESS.getMessage());
        baseResponse.setResponseTime(new Date());
        baseResponse.setData(object);
        return baseResponse;
    }

    public static BaseResponse success(Integer code, Object object) {
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setCode(code);
        baseResponse.setMsg(ResultEnum.SUCCESS.getMessage());
        baseResponse.setResponseTime(new Date());
        baseResponse.setData(object);
        return baseResponse;
    }

    public static BaseResponse success() {
        return success((Object)null);
    }

    public static BaseResponse error(String msg) {
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setCode(ResultEnum.SYSTEM_ERROR.getCode());
        baseResponse.setResponseTime(new Date());
        baseResponse.setMsg(msg);
        return baseResponse;
    }

    public static BaseResponse warn(int code, String msg) {
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setCode(code);
        baseResponse.setResponseTime(new Date());
        baseResponse.setMsg(msg);
        return baseResponse;
    }

    public static BaseResponse error(Integer code, String msg) {
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setCode(code);
        baseResponse.setResponseTime(new Date());
        baseResponse.setMsg(msg);
        return baseResponse;
    }

    /**
     * 使用response输出JSON
     * @author zwq
     * @date 2020-04-04
     **/
    public static void responseJson(ServletResponse response, BaseResponse result){
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            out = response.getWriter();
            out.println(JSON.toJSONString(result));
        } catch (Exception e) {
            log.error("【JSON输出异常】"+e);
        }finally{
            if(out!=null){
                out.flush();
                out.close();
            }
        }
    }
}
